const normalStyle = {
  "border-radius": "0 3px 3px 0",
  "font-weight": "400",
  color: "#fff",
  padding: "2px 16px",
  "font-size": "13px",
  "box-shadow": "0px 0px 5px black",
};

const transfromStyleToStr = (style) => {
  return JSON.stringify(style)
    .replace(/(\{|\})|(")/g, "")
    .replace(/,/g, ";");
};

class Logger {
  develepment = "development";

  constructor() {
    this.env = process.env.NODE_ENV;
    this.isDev = process.env.NODE_ENV === this.develepment;
  }

  logGroupCollapsed(data, str, style, isRequest = false, method) {
    if (!this.isDev) {
      console.log(this.env);
      return;
    }
    const b = isRequest ? "#39f" : "#191970";
    const r = {
      background: b,
      "border-radius": "3px 0 0 3px",
      width: "130px",
      padding: "2px 10px",
    };
    const p1 = transfromStyleToStr({ ...normalStyle, ...r });
    const p2 = transfromStyleToStr({ ...normalStyle, ...style });
    console.groupCollapsed(
      `%c${isRequest ? method : "response"}${str}`,
      p1,
      p2
    );
    const p3 = p2 + ";border-radius:3px";
    console.log(`%ctime ${new Date().toLocaleString()}`, p3);
    console.log(`%c${isRequest ? "params" : "result"}`, p3, data);
    console.groupEnd();
  }

  request(config) {
    const { url, method, data, params } = config;
    const p = method.toUpperCase() === "GET" ? params : data;
    const printStr = `%c${url}`;
    this.logGroupCollapsed(
      p,
      printStr,
      { background: "#778899" },
      true,
      method.toUpperCase()
    );
  }

  success(response) {
    const { config, data } = response;
    const printStr = `%c${config.url}`;

    this.logGroupCollapsed(data, printStr, { background: "#32CD32" });
  }

  warn(response) {
    const { config, data } = response;
    const printStr = `%curl: ${config.url}, failed: ${data.data}`;

    this.logGroupCollapsed(data, printStr, { background: "#f58220" });
  }

  error(response) {
    const { statusText, status, config } = response;
    const printStr = `%curl: ${config.url}, failed: ${status}-${statusText}`;

    this.logGroupCollapsed(response, printStr, { background: "#ef4136" });
  }
}

export default new Logger();
